import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:yurun_smartmerchants/models/tally_detail_entity.dart';
import 'package:yurun_smartmerchants/models/tallyallotrequest_entity.dart';
import 'package:yurun_smartmerchants/models/tobetally_response_entity.dart';
import 'package:yurun_smartmerchants/net/ApiInterface.dart';
import 'package:yurun_smartmerchants/res/colours.dart';
import 'package:yurun_smartmerchants/utils/app_size.dart';
import 'package:yurun_smartmerchants/utils/evenbus_utils.dart';
import 'package:yurun_smartmerchants/utils/loading_utils.dart';

class TallyDetailPage extends StatefulWidget {
  final TobetallyResponseResponseContent content;
  TallyDetailPage({Key key, @required this.content}) : super(key: key);
  @override
  _TallyDetailPagePageState createState() => _TallyDetailPagePageState();
}

class _TallyDetailPagePageState extends State<TallyDetailPage>
    with SingleTickerProviderStateMixin {
  var bus = EventBus();
  List<TallyDetailProduct> items = List();
  int position = 0;
  var weightControllerList = List<TextEditingController>();

  Map<String, dynamic> goodsMap = {};

  TallyDetailEntity tallyDetailEntity;
  TallyDetailProduct tallyDetailProduct = new TallyDetailProduct();

  @override
  void initState() {
    super.initState();
    print(widget.content.status);
    for (int i = 0; i < 1; i++) {
      position = i;
      items.add(tallyDetailProduct);
      weightControllerList.add(TextEditingController());
    }
    requestDetail();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text(widget.content.status == 0?'理货':'重新理货',
            style: TextStyle(fontSize: 18, color: Colours.app_words)),
        backgroundColor: Colours.title_bg,
        iconTheme: IconThemeData(color: Colours.app_words),
      ),
      body: Container(
        child: ListView.builder(
            itemCount: items.length,
            itemBuilder: (BuildContext context, int position) {
              if (position == 0) {
                return itemWidget(context, position);
              } else if (position == items.length - 1) {
                return bottomWidget(context, position);
              } else {
                return newitemWidget(context, position);
              }
            }),
      ),
    );
  }

  Widget itemWidget(BuildContext context, int index) {
    return Column(
      children: <Widget>[
        Container(
          margin: EdgeInsets.only(),
          width: double.infinity,
          height: AppSize.sp(196),
          color: Colours.white,
          alignment: Alignment.center,
          child: Stack(
            children: <Widget>[
              Container(
                color: Colors.white,
                height: AppSize.sp(180),
                child: Row(
                  children: <Widget>[
                    Container(
                      margin: EdgeInsets.only(
                          left: AppSize.sp(16),
                          top: AppSize.sp(16),
                          bottom: AppSize.sp(16)),
                      child: Image.network(
                        widget.content.categoryUrl,
                        width: AppSize.width(148),
                        height: AppSize.height(148),
                        fit: BoxFit.cover,
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(
                          left: AppSize.sp(5), top: AppSize.sp(16)),
                      child: Column(
                        children: <Widget>[
                          Text(
                            widget.content.categoryName,
                            style: TextStyle(fontSize: 18),
                            textAlign: TextAlign.left,
                          ),
                          Text(
                            widget.content.preWeight.toString() + '公斤',
                            style: TextStyle(
                              color: Colors.red,
                            ),
                          ),
                        ],
                      ),
                    ),
                    Spacer(),
                  ],
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  Widget newitemWidget(BuildContext context, int index) {
    return Column(children: <Widget>[
      Container(
        width: double.infinity,
        height: AppSize.sp(98),
        margin: EdgeInsets.only(top: AppSize.sp(index == 1 ? 20 : 0)),
        color: Colours.white,
        alignment: Alignment.center,
        child: Row(
          children: <Widget>[
            Container(
              margin: EdgeInsets.only(left: AppSize.sp(32)),
              child: Text(
                items[index].categoryiiiName == null
                    ? ''
                    : items[index].categoryiiiName,
                style: TextStyle(
                  fontSize: 18.0,
                ),
              ),
            ),
            Container(
              color: Colors.black12,
              margin: EdgeInsets.only(left: AppSize.sp(10)),
              child: Text(
                items[index].packageContainer == '散装'
                    ? items[index].packageContainer
                    : (items[index].quantity.toString() +
                        items[index].packageUnit.toString()),
                style: TextStyle(
                  fontSize: 12.0,
                  color: Colors.black,
//                  backgroundColor: Colors.brown,
                ),
              ),
            ),
            Expanded(
              child: Container(
//      color: Colors.red,
                margin: EdgeInsets.only(right: AppSize.sp(10)),
                child: TextField(
                  keyboardType: TextInputType.numberWithOptions(decimal: true),
                  controller: weightControllerList[index],
                  textAlign: TextAlign.right,
                  decoration: InputDecoration(
                    hintText: "输入理货数量",
                    hintStyle: TextStyle(
                      color: Colours.information_placeholder,
                    ),
                    border: InputBorder.none,
                  ),
                  style: TextStyle(),
                ),
              ),
            ),
            Container(
              margin: EdgeInsets.only(right: AppSize.sp(32)),
              child: Text(
                items[index].packageContainer == '散装'
                    ? '公斤'
                    : items[index].packageUnit.toString(),
                style: TextStyle(
                  fontSize: 18.0,
                ),
              ),
            )
          ],
        ),
      ),
    ]);
  }

  Widget bottomWidget(BuildContext context, int index) {
    return GestureDetector(
        onTap: () {

          TallyallotrequestEntity tallyallotrequestEntity = new TallyallotrequestEntity();
          tallyallotrequestEntity.products = new List<TallyallotrequestProduct>();
          tallyallotrequestEntity.id = widget.content.id;
          tallyallotrequestEntity.batchNo = widget.content.batchNo;

          for(int i=1;i<items.length-1;i++){
            TallyallotrequestProduct product = new TallyallotrequestProduct();
            product.id = items[i].id;
            product.tallyQuantity = double.parse(weightControllerList[i].text);
            print(weightControllerList[i].text);
            tallyallotrequestEntity.products.add(product);
          }
        comfirmTally(tallyallotrequestEntity);
        },
        child: Container(
            margin: EdgeInsets.only(
                left: AppSize.sp(32),
                right: AppSize.sp(32),
                top: AppSize.sp(64),
                bottom: AppSize.sp(64)),
            height: AppSize.height(68),
            alignment: Alignment.center,
            decoration: new BoxDecoration(
              color: Colours.app_main,
              borderRadius: BorderRadius.all(
                Radius.circular(AppSize.sp(6)),
              ),
            ),
            child: Container(
                alignment: Alignment.center,
                child: Text(
                  "确认理货",
                  style:
                      TextStyle(color: Colours.white, fontSize: AppSize.sp(32)),
                ))));
  }

  void comfirmTally(TallyallotrequestEntity entity) async {
    LoadingUtil.showLoading(context, tip: '请求中...');
    ApiInterface.confirmTally(entity).then((data) {
//      showToast('已理货成功');
    if(data != null){
      Future.delayed(Duration(seconds: 5),(){
        Navigator.of(context).pop();
      });
    }
      print(data.toString());

    }).catchError((error){
      setState(() {});
    }).whenComplete(() => LoadingUtil.hideLoading(context));

  }


  Widget getItem(BuildContext context, int index) {
    return Container(
      margin: EdgeInsets.only(bottom: AppSize.sp(20)),
      child: Column(
        children: <Widget>[
          Container(
            color: Colours.color_f8f8f8,
            width: double.infinity,
            height: AppSize.height(64),
            alignment: Alignment.center,
            child: Row(
              children: <Widget>[
                Container(
                  margin: EdgeInsets.only(
                      left: AppSize.sp(19), right: AppSize.sp(16)),
                  width: AppSize.width(5),
                  height: AppSize.height(28),
                ),
                Text(
                  "批次号: ",
                  style: TextStyle(
                      color: Colours.color_313131, fontSize: AppSize.sp(32)),
                ),
                Spacer(),
                Container(
                  margin: EdgeInsets.only(right: AppSize.sp(32)),
                  child: Text(
                    '时间',
                    style: TextStyle(
                        fontSize: AppSize.sp(26), color: Colours.color_898989),
                  ),
                )
              ],
            ),
          ),
          Container(
            width: double.infinity,
            height: AppSize.height(178),
            color: Colours.white,
            alignment: Alignment.center,
            child: Row(
              children: <Widget>[
                Container(
                  margin: EdgeInsets.only(
                      left: AppSize.sp(16),
                      top: AppSize.sp(16),
                      bottom: AppSize.sp(16)),
                  child: Image.network(
                    'URL',
                    width: AppSize.width(178),
                    height: AppSize.height(146),
                    fit: BoxFit.cover,
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(
                      left: AppSize.sp(10), top: AppSize.sp(32)),
                  child: Column(
                    children: <Widget>[
                      Text(
                        '标题',
                        style: TextStyle(fontSize: 18),
                      ),
                      Text(
                        '重量' + '/公斤',
                        style: TextStyle(
                          color: Colors.red,
                        ),
                      ),
                    ],
                  ),
                ),
                Spacer(),
                Container(
                  margin: EdgeInsets.only(right: AppSize.sp(30)),
                  child: RaisedButton(
                    child: Text('重新理货'),
                    color: Colors.red,
                    textColor: Colors.white,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(5),
                    ),
                    onPressed: () {

                    },
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  void requestDetail() async {
    ApiInterface.tallyDetail(widget.content.id, 0, widget.content.categoryId)
        .then((data) {
      tallyDetailEntity = TallyDetailEntity().fromJson(data);
      if (tallyDetailEntity.products != null &&
          tallyDetailEntity.products.length > 0) {
        for (int i = 0; i < tallyDetailEntity.products.length; i++) {
          position += (i + 1);
          items.add(tallyDetailEntity.products[i]);
          weightControllerList.add(TextEditingController());
        }
      }
      items.add(tallyDetailProduct);
      weightControllerList.add(TextEditingController());
      setState(() {});
    }).catchError((error) {});
  }
}
